package com.dream.service.basic;

import com.dream.common.constans.RedisKeysDefine;
import com.dream.common.utils.JsonUtils;
import com.dream.common.utils.payutils.NumberUtils;
import com.dream.common.utils.payutils.bean.MessageBeanOld;
import com.dream.common.utils.payutils.bean.WorkedRedPackageBean;
import com.dream.dto.console.StatisticsSum;
import com.dream.dto.response.GroupMemberRedPack;
import com.dream.dto.response.GroupMemberRedPackPicker;
import com.dream.dto.socket.SocketBean;
import com.dream.mapper.RedPackagePickMapper;
import com.dream.mapper.RedPackageSendMapper;
import com.dream.mapper.UserFieldMapper;
import com.dream.web.websocket.ConsoleWebSocket;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class AsyncInvokeService {

    @Resource
    private RedPackageSendMapper redPackageSendMapper;
    @Resource
    private RedisCacheService redisCacheService;
    @Resource
    private RedPackagePickMapper redPackagePickMapper;
    @Resource
    private ConsoleWebSocket consoleWebSocket;
    @Resource
    private UserFieldMapper userFieldMapper;

    /**
     * 上传红包后发送web端首页
     */
    @Async
    public void informIndexDPanel(WorkedRedPackageBean workedRedPackageBean, MessageBeanOld messageBean, int playType) {
        redPackagePickMapper.insertList(workedRedPackageBean.pickUserList);
        redPackageSendMapper.insert(workedRedPackageBean);
        //message write db;
        msgUnityWrite(workedRedPackageBean.bijiAccount, JsonUtils.toJSONString(messageBean));
        StatisticsSum statisticsSum = redisCacheService.getObject(RedisKeysDefine.STATISTICS_PANEL.
                concat(workedRedPackageBean.bijiAccount), StatisticsSum.class);
        if (statisticsSum != null) {
            statisticsSum.sendMoney = NumberUtils.add(statisticsSum.sendMoney, workedRedPackageBean.sendMoney == null ? 0 : workedRedPackageBean.sendMoney);
            statisticsSum.stealMoney = NumberUtils.add(statisticsSum.stealMoney, workedRedPackageBean.stealMoney == null ? 0 : workedRedPackageBean.stealMoney);
            statisticsSum.thunderMoney = NumberUtils.add(statisticsSum.thunderMoney, workedRedPackageBean.thunderMoney == null ? 0 : workedRedPackageBean.thunderMoney);
            statisticsSum.allRewardsMoney = NumberUtils.add(statisticsSum.allRewardsMoney, workedRedPackageBean.allRewardsMoney == null ? 0 : workedRedPackageBean.allRewardsMoney);
            statisticsSum.noDeadPickMoney = NumberUtils.add(statisticsSum.noDeadPickMoney, workedRedPackageBean.noDeadPickMoney == null ? 0 : workedRedPackageBean.noDeadPickMoney);
            statisticsSum.sendNumber += 1;
        } else {
            //不存在为空情况，db已做空行为0处理
            statisticsSum = redPackageSendMapper.selectSumByUser(workedRedPackageBean.bijiAccount);
        }
        //处理盈利琻额
        if (playType == 0) {//襟枪
            statisticsSum.profitMoney = NumberUtils.subtract(statisticsSum.sendMoney, statisticsSum.thunderMoney);
            statisticsSum.profitMoney = NumberUtils.subtract(statisticsSum.profitMoney, statisticsSum.stealMoney);
        } else {//可枪或者接龙
            statisticsSum.profitMoney = NumberUtils.subtract(statisticsSum.noDeadPickMoney, statisticsSum.allRewardsMoney);
        }
        statisticsSum.historyMsg = Collections.singletonList(JsonUtils.toJSONString(messageBean));
//        statisticsSum.workedRedPackageBean = Collections.singletonList(workedRedPackageBean);
        statisticsSum.groupRedPackList = getMergedGroupRedPackList(workedRedPackageBean.bijiAccount);
        redisCacheService.setObject(RedisKeysDefine.STATISTICS_PANEL.
                concat(workedRedPackageBean.bijiAccount), statisticsSum);
        SocketBean socketBean = new SocketBean();
        socketBean.command = 10;
        socketBean.data = JsonUtils.toJSONString(statisticsSum);
        consoleWebSocket.sendMessageToUser(workedRedPackageBean.bijiAccount, JsonUtils.toJSONString(socketBean));
    }

    /**
     * 合并伐包和枪包数据
     *
     * @param bijiAccount
     * @return
     */
    public List<GroupMemberRedPack> getMergedGroupRedPackList(String bijiAccount) {
        List<GroupMemberRedPack> senderList = redPackageSendMapper.selectGroupSumByUser(bijiAccount);
        Set<String> sendIdSet = new HashSet();
        for (GroupMemberRedPack sender : senderList) {
            sendIdSet.add(sender.sendUserId);
        }
        List<GroupMemberRedPackPicker> pickerList = redPackagePickMapper.selectPickUserGroupByUserID(bijiAccount);
        //拼装数据
        for (GroupMemberRedPackPicker picker : pickerList) {
            if (!sendIdSet.contains(picker.userId)) {
                GroupMemberRedPack newSender = new GroupMemberRedPack();
                newSender.sendUserId = picker.userId;
                newSender.sendUsername = picker.username;
                newSender.sendHeadImage = picker.userHeadImage;
                senderList.add(newSender);
            }
        }
        for (GroupMemberRedPack sender : senderList) {
            for (GroupMemberRedPackPicker picker : pickerList) {
                if (sender.sendUserId.equals(picker.userId)) {
                    sender.pickNumber = picker.pickNumber;
                    sender.pickMoney = picker.pickMoney;
                    sender.rewardsMoney = picker.rewardsMoney;
                }
            }
        }
        for (GroupMemberRedPack sender : senderList) {
            sender.profitMoney = NumberUtils.add(sender.thunderMoney == null ? 0 : sender.thunderMoney, sender.rewardsMoney == null ? 0 : sender.rewardsMoney);
            sender.profitMoney = NumberUtils.add(sender.profitMoney == null ? 0 : sender.profitMoney, sender.pickMoney == null ? 0 : sender.pickMoney);
            sender.profitMoney = NumberUtils.subtract(sender.profitMoney == null ? 0 : sender.profitMoney, sender.sendMoney == null ? 0 : sender.sendMoney);
        }
        return senderList;
    }


    /**
     * 消息统一记录
     *
     * @param userName
     * @param msg
     */
    @Async
    public void msgUnityWrite(String userName, String msg) {
        BaseServiceHelper.getRedisCacheService().zSetOperations.add(RedisKeysDefine.IM_MSG.concat(userName),
                msg, System.currentTimeMillis());
//        userFieldMapper.insert(UserField.builder().userName(userName).optionKey(Constants.IM_MSG)
//                .optionValue(msg).build());
    }


}
